02.webview_flutter Cookie 管理
在 webview_flutter 中,WebViewCookieManager 类负责 Cookie 管理。
设置 Cookie
Future<void> setCookie(WebViewCookie cookie)
=> platform.setCookie(cookie);
清空 Cookie
Future<bool> clearCookies() => platform.clearCookies();
实例代码:
Future<void> _onClearCookies(BuildContext context) async {
final bool hadCookies = await cookieManager.clearCookies();
String message = 'There were cookies. Now, they are gone!';
if (!hadCookies) {
message = 'There are no cookies.';
}
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
));
}
}
获取 Cookies
Future<void> _onListCookies(BuildContext context) async {
final String cookies = await webViewController
.runJavaScriptReturningResult('document.cookie') as String;
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Cookies:'),
_getCookieList(cookies),
],
),
));
}
}
Widget _getCookieList(String cookies) {
if (cookies == '""') {
return Container();
}
final List<String> cookieList = cookies.split(';');
final Iterable<Text> cookieWidgets =
cookieList.map((String cookie) => Text(cookie));
return Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: cookieWidgets.toList(),
);
}
获取底层平台实现
WebViewCookieManager 的 platform 中包含了对应平台下的具体实现类,获取方法:
PlatformWebViewCookieManagerCreationParams params =
const PlatformWebViewCookieManagerCreationParams();
if (WebViewPlatform.instance is WebKitWebViewPlatform) {
params = WebKitWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
params,
);
} else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
params = AndroidWebViewCookieManagerCreationParams
.fromPlatformWebViewCookieManagerCreationParams(
params,
);
}
final WebViewCookieManager webViewCookieManager =
WebViewCookieManager.fromPlatformCreationParams(
params,
);
网络资源
本文作者:Maeiee
本文链接:02.webview_flutter Cookie 管理
版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!
喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!